﻿namespace il.lua;

public interface ICodeWriter
{
    int Indent { get; set; }
    void Code(object value);
    void CodeLn(object value = null);
    void CommentLn(object value);
}

public class CodeWriter : ICodeWriter
{
    private bool _newLine;
    private readonly TextWriter _writer;

    public CodeWriter(TextWriter writer)
    {
        _writer = writer;
    }

    public int Indent { get; set; }

    public virtual void Code(object? value)
    {
        NewLine();
        _writer.Write(value);
    }

    public virtual void CodeLn(object? value = null)
    {
        NewLine();
        if (value != null)
            _writer.WriteLine(value);
        else
            _writer.WriteLine();
        _newLine = true;
    }

    public virtual void CommentLn(object value)
    {
        CodeLn($"-- {value}");
    }

    private void NewLine()
    {
        if (_newLine)
        {
            _newLine = false;
            var count = Indent * 4;
            for (var i = 0; i < count; i++)
            {
                _writer.Write(' ');
            }
        }
    }
}